using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;

namespace UDART
{
    public class Comm
    {
        Configuration _config = new Configuration();
        private SerialPort _serialPort = new SerialPort();

        public Comm()
        {
            _serialPort.PortName = _config.Com_Port;
            _serialPort.BaudRate = _config.Baud_Rate;
            _serialPort.ReadTimeout = _config.Timeout;
            _serialPort.Open();
        }

        #region Member Functions

        // Sends a command and returns the response
        public string SendCommand(string command)
        {
            try
            {
                _serialPort.WriteLine(command);
                return _serialPort.ReadLine();
            }
            catch (TimeoutException)
            {
                return "TIMEOUT";
            }
            catch
            {
                return "COMM ERROR";
            }
        }

        // Sends a string
        public bool Send(string command)
        {
            try
            {
                _serialPort.WriteLine(command);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        // Read a line
        public string ReadLine()
        {
            try
            {
                return _serialPort.ReadLine();
            }
            catch (TimeoutException)
            {
                return "TIMEOUT";
            }
            catch
            {
                return "COMM ERROR";
            }
        }

        // Close Port
        public void Close()
        {
            _serialPort.Close();
        }

        #endregion
    }
}
